#!/bin/bash
#Author: YangYi
#Date: 2025-03-28
#Version: v1
#Content 一键诊断、处置原子能力，node组件检测列表
#1.kube-proxy
#2.kubelet
#3.docker/crictl
#4.证书有效期


# 检查是否传入了参数
if [ -z "$1" ]; then
  echo "Usage: $0 <请输入您需要诊断的节点IP: 10.145.xxx.xxx>"
  exit 1
fi

# 节点IP获取
IP=$1


# ---------------------------初始化全局变量----------------------------

# 颜色定义
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
RED='\033[0;31m'
NC='\033[0m'

# 初始化退出码
EXIT_CODE=0

#全局状态码
CODE=""

# ----------------------------功能模块函数-----------------------------

# 检查systemd服务状态
check_service() {
    SERVICE_NAME=$1
    echo -n "检查 $SERVICE_NAME 服务状态... "
    
    if systemctl is-active --quiet "$SERVICE_NAME"; then
        echo -e "${GREEN}服务运行中${NC}"
    else
        echo -e "${RED}服务未运行${NC}"
        EXIT_CODE=1
    fi
}

# 检查容器状态
check_container() {
    CONTAINER_NAME=$1
    echo -n "检查 $CONTAINER_NAME 服务状态... "
    
    if sudo docker ps --filter "name=$CONTAINER_NAME" --format "{{.Names}}" | grep -q "$CONTAINER_NAME"; then
        STATUS=$(sudo docker ps --filter "name=$CONTAINER_NAME"  --format '{{.State}}' | head -1 )
        if [ "$STATUS" == "running" ]; then
            echo -e "${GREEN}服务运行中${NC}"
        else
            echo -e "${YELLOW}$STATUS${NC}"
            EXIT_CODE=1
        fi
    else
        echo -e "${RED}未找到服务${NC}"
        EXIT_CODE=1
    fi
}

# 检查证书有效期
check_certificate() {
    CERT_PATH=$1
    CERT_NAME=$(basename "$CERT_PATH")
    echo -n "检查 $CERT_NAME 有效期... "

    if [ ! -f "$CERT_PATH" ]; then
        echo -e "${RED}证书未找到${NC}"
        EXIT_CODE=1
        return
    fi

    EXPIRY_DATE=$(sudo openssl x509 -in "$CERT_PATH" -noout -enddate | awk -F= '{print $2}')
    CURRENT_DATE=$(date +%s)
    EXPIRY_DATE_EPOCH=$(sudo date -d "$EXPIRY_DATE" +%s 2>/dev/null)

    if [ -z "$EXPIRY_DATE_EPOCH" ]; then
        echo -e "${YELLOW}无法解析有效期格式${NC}"
        return
    fi

    DAYS_LEFT=$(( (EXPIRY_DATE_EPOCH - CURRENT_DATE) / 86400 ))

    if [ $DAYS_LEFT -lt 0 ]; then
        echo -e "${RED}已过期 (过期时间: $EXPIRY_DATE)${NC}"
        EXIT_CODE=1
    elif [ $DAYS_LEFT -lt 30 ]; then
        echo -e "${YELLOW}剩余 $DAYS_LEFT 天过期 (过期时间: $EXPIRY_DATE)${NC}"
    else
        echo -e "${GREEN}有效期正常 (剩余 $DAYS_LEFT 天)${NC}"
    fi
}

# 主检查流程
main() {
    echo -e "\n${YELLOW}=== node组件状态检查 ===${NC}"
    # 检查系统服务
    check_service kubelet
    check_service docker

    # 检查容器
    check_container kube-proxy

    echo -e "\n${YELLOW}=== 证书有效期检查 ===${NC}"
    # Kubelet证书检查
    check_certificate "/var/lib/kubelet/pki/kubelet.crt"
    check_certificate "/var/lib/kubelet/pki/kubelet-client-current.pem"
    
    # 退出码处理
    if [ $EXIT_CODE -eq 0 ]; then
	CODE=200
        echo -e "\n${GREEN}$CODE 所有检查通过！${NC}"
    else
	CODE=2000
        echo -e "\n${RED}$CODE 发现异常项，请检查上述报告！${NC}"
    fi

    exit $EXIT_CODE
}

# 执行主函数
main
